package com.fiberhome.app.network.socket;

import android.text.TextUtils;

import com.fiberhome.app.network.CacheSender;
import com.fiberhome.app.network.Failure;
import com.fiberhome.app.network.IData;
import com.fiberhome.app.network.cache.CacheUtil;
import com.fiberhome.app.network.parse.Parser;

import java.io.IOException;

import io.reactivex.annotations.NonNull;

/**
 * Created by Deed on 2018/1/9.
 */

public abstract class SocketSender extends CacheSender {

    private SocketBuilder sb;

    /**
     *
     * @param sb SocketBuilder
     */
    SocketSender(@NonNull SocketBuilder sb) {
        super(sb);
        this.sb = sb;
    }

    /**
     *
     * @return String
     * @throws IOException
     */
    protected abstract String send() throws IOException;


    /**
     *
     * @param cls Class<T>
     * @param <T> extends IData
     * @return IData
     */
    @Override
    protected <T extends IData> IData getRemoteData(Class<T> cls) {
        IData data;
        try {
            String result = send();
            if (!TextUtils.isEmpty(result)) {
                data = Parser.parseTo(result, cls);
                if (data == null) {
                    data = new Failure(Failure.ERROR_DATA_PARSE,"Data format error");
                } else {
                    CacheUtil.myCache().put(sb, data, result);
                }
            } else {
                data = new Failure(Failure.ERROR_DATA_NULL,"Empty data");
            }

        } catch (IOException e) {
            e.printStackTrace();
            data = new Failure(Failure.ERROR_CONNECT,e.getMessage());
        }
        return data;
    }


}
